package io.hellsinger.navigation.screen

import android.content.Context
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.WindowInsets
import android.view.WindowManager.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import android.widget.PopupWindow

class HostNavPopupView(
    context: Context,
) : FrameLayout(context) {
    private var window: PopupWindow? = null
    var scrim =
        View(context).apply {
            layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT)
            setBackgroundColor(0x32000000)
            setOnApplyWindowInsetsListener { v, insets ->
                val top =
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        insets.getInsets(WindowInsets.Type.statusBars()).top
                    } else {
                        insets.systemWindowInsetTop
                    }
                v.setPadding(
                    v.left,
                    top,
                    v.right,
                    v.bottom,
                )
                insets
            }
        }

    init {
        addView(scrim)
    }

    fun hide() {
        window?.dismiss()
    }

    fun create() {
        window =
            PopupWindow(this, MATCH_PARENT, MATCH_PARENT)
    }

    fun show(anchor: View) {
        window?.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, 0)
    }
}
